package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice //指定当前类 是统一异常处理类
public class BaseExceptionCache {

    @ExceptionHandler(RuntimeException.class) //指定抓取的异常类
    public ResponseResult runTimeExceptionHandler(RuntimeException e){

        return ResponseResult.error(500,e.getMessage());

    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException e){
        return ResponseResult.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult notValidExceptionHandler(MethodArgumentNotValidException e){

        List<ObjectError> objectErrorList = e.getBindingResult().getAllErrors();

//        String msg = "";
//        for (ObjectError objectError : objectErrorList) {
//            String emsg = objectError.getDefaultMessage();
//            if(msg.length()>0){
//                msg +=",";
//            }
//            msg+= emsg;
//        }
//        流
        String msg = objectErrorList.
                stream().
                map(ObjectError::getDefaultMessage).
                collect(Collectors.joining(","));

        return ResponseResult.error(400,msg);
    }

}
